package com.audaque.springboot.foshanupload.security.filter;

import com.audaque.springboot.foshanupload.authcore.properties.LoginProperties;
import com.audaque.springboot.foshanupload.security.exception.CaptchaException;
import com.audaque.springboot.foshanupload.security.handler.MyUrlAuthenticationFailureHandler;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*CaptchaFilter用于验证码验证
 * 因为验证码值需要一次校验，所以继承OncePerRequestFilter
 * 自己写的过滤器要在security配置类中配置
 * */
@Slf4j
public class MyCaptchaFilter extends OncePerRequestFilter {


    @Autowired
    private MyUrlAuthenticationFailureHandler myUrlAuthenticationFailureHandler;

    @Autowired
    private LoginProperties loginProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("开始验证码验证");
        String url = request.getRequestURI();
        //只有登陆时才会验证验证码
        if (loginProperties.getLoginUrl().equals(url) && request.getMethod().equals("POST")) {
            try {
                //校验验证码
                String key = request.getParameter("captchaKey");
                String code = request.getParameter("captchaCode");
                if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) {
                    throw new CaptchaException("验证码信息为空");
                }
                if (false) {
                    throw new CaptchaException("验证码错误");
                }
                //删除redis的验证码，保证每个验证码只使用一次:安全
                // 校验成功才放行
                filterChain.doFilter(request, response);
            } catch (CaptchaException e) {
                //发现异常，则交给登录失败处理器
                myUrlAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        //将请求转发给下一个过滤器
        filterChain.doFilter(request, response);
    }

}
